<?php
/**
 * Created by PhpStorm.
 * User: zq
 * Date: 2017/2/23
 * Time: 16:45
 */

namespace Admin\Controller;


use Common\Controller\AdminController;
use Common\Model\DetailModel;
use Common\Model\GoodsAttrModel;
use Common\Model\GoodsModel;
use Common\Model\TypeAttrModel;

class GoodsController extends AdminController
{
    protected $db;

    public function __init()
    {
        $this->db = new GoodsModel();
    }

    public function index()
    {
        $model = M('Goods'); // 实例化User对象
        $count = $model->count();// 查询满足要求的总记录数
        $Page = new \Think\Page($count, 3);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        //dd($Page);
        $Page->setConfig('header', "共 <span style='color:red'>%TOTAL_ROW%</span> 条记录");
        $Page->setConfig('prev', '上一楼');
        $Page->setConfig('next', '下一楼');
        $Page->setConfig('theme', "%HEADER% %FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END%");
        $show = $Page->show();// 分页显示输出
// 进行分页数据查询 注意limit方法的参数要使用Page类的属性
        $list = $model->order('time')->limit($Page->firstRow . ',' . $Page->listRows)->select();
//		dd($show);
//		dd($list);
        $this->assign('list', $list);// 赋值数据集
        $this->assign('page', $show);// 赋值分页输出
        $this->display();
    }

    public function store()
    {
        if (IS_POST) {
            $res = $this->db->store();
            if ($res['valid']) {
                $this->success($res['message'], u('index'));
                die;
            }
            $this->error($res['message']);
            die;
        }
        //1.获取所有分类数据
        $cateData = $this->db->getCateData();
        $this->assign('cateData', $cateData);
        //2.获取所有品牌数据
        $brandData = $this->db->getBrandData();
        $this->assign('brandData', $brandData);

        $this->display();
    }

    //异步上传图片
    public function ajaxUpload()
    {
        //调用框架上传类来处理
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 3145728;// 设置附件上传大小
        $upload->exts = ['jpg', 'gif', 'png', 'jpeg'];// 设置附件上传类型
        $upload->rootPath = './Uploads/'; // 设置附件上传根目录
        $upload->savePath = ''; // 设置附件上传（子）目录
        // 上传文件
        //current  获取兼键值，在这转为一维数组
        $info = current($upload->upload());
        $path = 'Uploads/' . $info['savepath'] . $info['savename'];
        echo $path;
        exit;
    }

    //异步删除图片
    public function ajaxDelImg()
    {
        if (IS_AJAX) {
            $path = $_POST['path'];
            if (file_exists($path)) {
                unlink($path);
            }
        }
    }

    /**
     * 异步获取规格和属性
     */
    public function ajaxGetAttr()
    {
        //在类型属性表中根据tid找数据
        if (IS_AJAX) {
            $tid = I('post.tid');
            //dd($tid);
            $data = (new TypeAttrModel())->where("tid={$tid}")->select();
            //将tavalue转为数组
            foreach ($data as $k => $v) {
                $data[$k]['avalue'] = explode(',', $v['avalue']);
            }
            //dd($data);die;
            $this->ajaxReturn($data);
        }
    }

    public function edit()
    {
        if (IS_POST) {
            $res = $this->db->edit();
            if ($res['valid']) {
                $this->success($res['message'], u('index'));
                die;
            }
            $this->error($res['message']);
            die;
        }
        $gid = I('get.gid');

//        dump($gid);
        //1.获取所有分类数据
        $cateData = $this->db->getCateData();
        //dd($cateData);
        $this->assign('cateData', $cateData);
        //2.获取品牌数据
        $brandData = $this->db->getBrandData();
        //dd($brandData);
        $this->assign('brandData', $brandData);
        $GoodsData = m('goods')->find($gid);
//        dump($GoodsData);die;
        $this->assign('GoodsData', $GoodsData);
        //关联商品表和商品详情表获取旧数据
        $oldData = $this->db->alias('g')
            ->join('sh_detail gd ON g.gid = gd.gid')
            ->where("gd.gid={$gid}")->find();
//        dump($oldData);die;
        //将大图转换为数据
        $oldData['big'] = explode(',', $oldData['big']);
//
        //处理属性数据
        $attrData = (new TypeAttrModel())->where("tid={$oldData['tid']} and class=0")->select();
//        dump($attrData);die;
        foreach ($attrData as $k => $v) {
            $attrData[$k]['avalue'] = explode(',', $v['avalue']);
        }
        //dump($attrData);die;
        //获取添加时添加了那些属性
        $hasAddAttr = (new GoodsAttrModel())->where("gid =$gid")->
                         getField("gtvalue", true);
        //dump($hasAddAttr);die;
        //处理规格数据[类型属性表和商品属性表关联]
        $specData = (new TypeAttrModel())->alias('ta')
            ->join('sh_goods_attr ga on ta.aid=ga.aid')
            ->where("ga.gid=$gid and ta.class=1")->select();
//        dump($specData);die;
        foreach($specData as $k=>$v)
        {
            $specData[$k]['avalue'] = explode(',',$v['avalue']);
        }
//        dd($specData);die;
        $this->assign('specData',$specData);
        $this->assign('hasAddAttr',$hasAddAttr);
        $this->assign('attrData',$attrData);
        $this->assign('oldData',$oldData);

        $this->display();
    }
    public function del(){
        $gid =I('get.gid');
//        dump($gid);die;
        $model = new GoodsModel();
        $res = $model->where("gid={$gid}")->delete();
        if($res){
            $res1 =M('goods_attr')->where("gid={$gid}")->delete();
        }
        if($res1){
            $res2 = M('detail')->where("gid={$gid}")->delete();
        }
        if($res2){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }

    }


}